package com.gyg.threadPool;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * 动态变更线程池参数
 */
@Slf4j
public class ThreadChangeDemo {
    /**
     * 核心线程数
     */
    private static final int CORE_POOL_SIZE = 2;
    /**
     * 最大线程数
     */
    private static final int MAX_POOL_SIZE = 5;
    /**
     * 保持连接时间
     */
    private static final long KEEP_ALIVE_TIME = 1;
    /**
     * 队列长度
     */
    private static final int QUEUE_CAPACITY = 10;
    /**
     * 时间单位
     */
    private static final TimeUnit TIME_UNIT = TimeUnit.SECONDS;

    public static void main(String[] args) {
        dynamicModifyExecutor();
    }

    public static ThreadPoolExecutor createThreadPoolExecutor() {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
                MAX_POOL_SIZE,
                KEEP_ALIVE_TIME,
                TIME_UNIT,
                new LinkedBlockingQueue<>(QUEUE_CAPACITY),
                new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolExecutor;
    }

    /**
     * 先提交任务给线程池，再修改线程池参数
     */
    public static void dynamicModifyExecutor() {
        ThreadPoolExecutor pool = createThreadPoolExecutor();
        for (int i = 0; i < 15; i++) {
            pool.submit(() -> {
                threadPoolStatus(pool, "创建任务");
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        threadPoolStatus(pool, "改变之前");
        //将核心线程数改为10
        pool.setCorePoolSize(5);
        //将最大线程数改为10
        pool.setMaximumPoolSize(10);
        threadPoolStatus(pool, "改变之后");
        pool.shutdown();
    }

    /**
     * 获取线程池状态
     *
     * @param pool 线程池
     * @param name 名称
     */
    public static void threadPoolStatus(ThreadPoolExecutor pool, String name) {
        LinkedBlockingQueue<Runnable> queue = (LinkedBlockingQueue<Runnable>) pool.getQueue();
        log.info(Thread.currentThread().getName() + " " + name + " "
                + "核心线程数：" + pool.getCorePoolSize() + " "
                + "活动线程数：" + pool.getActiveCount() + " "
                + "最大线程数：" + pool.getMaximumPoolSize() + " "
                + "任务完成数：" + pool.getCompletedTaskCount() + " "
                + "队列大小：" + (queue.size() + queue.remainingCapacity()) + " "
                + "当前排队线程数：" + queue.size() + " "
                + "队列剩余大小：" + queue.remainingCapacity()
        );
    }
}
